/*
 * Copyright (C) 2013 by KB3ZYT Richard Nash
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <SoftwareSerial.h>
#include <SD.h>  // Uses 6020 program memory bytes
#include <Wire.h>

#include <APRS_HEADERS.h>   // Uses 3142 program memory bytes
#include <DHT.h>
#include <BMP085.h>
#include <MemoryFree.h>

#include "GPS.h"
#include "BalloonStateMachine.h"
#include "Utils.h"

#define SD_CHIPSELECT_PIN 8
#define SD_PIN10

// Statics

// The Adafruit "Ultimate" GPS
// The GPS is wired as a serial port on digital pins 6,7
#define GPS_RX 6
#define GPS_TX 7
SoftwareSerial gpsSerial(GPS_TX, GPS_RX);
GPS gps(&gpsSerial); // GPS Controller

BalloonStateMachine balloon;

void setupGPS()
{
    gps.init(9600); 
    // Turn on GGA (fix data) including altitude
    gps.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
    // Set the update rate
    gps.sendCommand(PMTK_SET_NMEA_UPDATE_POINT1HZ);   // 0.1 Hz update rate
}

void setup()
{
    Serial.begin(115200);
    printMem(F("setup"));
    Wire.begin();
    // make sure that the default chip select pin is set to
    // output, even if you don't use it for the SD card.
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
    // see if the card is present and can be initialized:
    if (!SD.begin(SD_CHIPSELECT_PIN)) {
        Serial.println(F("SD failed"));
    }    
    setupGPS();
    printMem(F("setup end"));  
}

void loop()
{        
    uint8_t parsed = gps.recieveGPSSentence();
    if (parsed == PARSED_SOMETHING) { 
        // Every 10 seconds we will get new sentences and can act on them
        printMem(F("location recieved"));
        balloon.pumpState(gps);
    }
}

